/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package facturacion;

import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
//import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
//import javax.swing.WindowConstants;
import java.util.Calendar;

/**
 *
 * @author CEBALLOS
 */
public final class f_salidas extends javax.swing.JFrame {

    /**
     * Creates new form Productos
     */
    public f_salidas() {
        
        initComponents();
        conectar();
       
       
        TxtIdOut.setEnabled(false);
        GuardarOut.setEnabled(false);
        BtnCancelarOut.setEnabled(false);
        
               
        cargarfecha();
       
      
    }
    
    int Constante =100;// constante para valores en DB EX_MAX  EX_MIN
    
    
    @Override
    public Image getIconImage(){
    
        Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("IMAGENES/icon.png"));
    return retValue;
    }
   
    Connection conexion,conexionout;  //  @jve:decl-index=0:
    Statement sentencia,sentenciaout,sentenciaxreg,sentenciaxregout;  //  @jve:decl-index=0:
    ResultSet resultado,resultadoout,resultadoventas,resultadoxreg,resultadoxregout;
    int xregistros,xregistrosout;
    boolean nuevoreg;
    boolean nuevoregout;
    String elcodigo= ""; 
    String elcodigoout= ""; 
    Calendar lafecha = Calendar.getInstance();
    Calendar lafechaout = Calendar.getInstance();
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        TxtPVP = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        BtnPrimerOut = new javax.swing.JButton();
        BtnAnteriorOut = new javax.swing.JButton();
        BtnBuscarOut = new javax.swing.JButton();
        BtnSiguienteOut = new javax.swing.JButton();
        BtnUltimoOut = new javax.swing.JButton();
        jLabelIdOut = new javax.swing.JLabel();
        TxtIdOut = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        TxtObservacionOut = new javax.swing.JTextField();
        jLabelObservaciones = new javax.swing.JLabel();
        jLabelMontoOut = new javax.swing.JLabel();
        TxtMontoOut = new javax.swing.JTextField();
        TxtFecha = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        NuevoOut = new javax.swing.JButton();
        GuardarOut = new javax.swing.JButton();
        BtnCancelarOut = new javax.swing.JButton();
        BtnSalirOut = new javax.swing.JButton();

        TxtPVP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TxtPVPActionPerformed(evt);
            }
        });
        TxtPVP.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                TxtPVPKeyTyped(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("FORMULARIO DE SALIDAS DE CAJA");
        setIconImage(getIconImage());
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 255, 0)));

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        BtnPrimerOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/PRIMERO.JPG"))); // NOI18N
        BtnPrimerOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnPrimerOutActionPerformed(evt);
            }
        });

        BtnAnteriorOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/ANTERIOR.JPG"))); // NOI18N
        BtnAnteriorOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnAnteriorOutActionPerformed(evt);
            }
        });

        BtnBuscarOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/BUSCAR.JPG"))); // NOI18N
        BtnBuscarOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnBuscarOutActionPerformed(evt);
            }
        });

        BtnSiguienteOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/SIGUIENTE.JPG"))); // NOI18N
        BtnSiguienteOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnSiguienteOutActionPerformed(evt);
            }
        });

        BtnUltimoOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/ULTIMO.JPG"))); // NOI18N
        BtnUltimoOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnUltimoOutActionPerformed(evt);
            }
        });

        jLabelIdOut.setText("ID SALIDA");

        TxtIdOut.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelIdOut)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(TxtIdOut, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(BtnPrimerOut, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnAnteriorOut, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnBuscarOut, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnSiguienteOut, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnUltimoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(TxtIdOut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelIdOut)))
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(BtnPrimerOut, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BtnAnteriorOut, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BtnBuscarOut, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BtnSiguienteOut, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(BtnUltimoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabelObservaciones.setText("OBSERVACIONES");

        jLabelMontoOut.setText("VALOR $");

        TxtMontoOut.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                TxtMontoOutFocusLost(evt);
            }
        });
        TxtMontoOut.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                TxtMontoOutKeyTyped(evt);
            }
        });

        TxtFecha.setEditable(false);
        TxtFecha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                TxtFechaFocusGained(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("ENTRADAS");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(TxtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabelMontoOut)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(TxtMontoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabelObservaciones)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(TxtObservacionOut, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(10, 10, 10))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TxtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelMontoOut)
                    .addComponent(TxtMontoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TxtObservacionOut, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelObservaciones))
                .addContainerGap())
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        NuevoOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/NUEVO.JPG"))); // NOI18N
        NuevoOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NuevoOutActionPerformed(evt);
            }
        });

        GuardarOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/GUARDAR2.JPG"))); // NOI18N
        GuardarOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GuardarOutActionPerformed(evt);
            }
        });

        BtnCancelarOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/CANCELAR.JPG"))); // NOI18N
        BtnCancelarOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelarOutActionPerformed(evt);
            }
        });

        BtnSalirOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/IMAGENES/SALIR.JPG"))); // NOI18N
        BtnSalirOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnSalirOutActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(NuevoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(GuardarOut, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnCancelarOut, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(BtnSalirOut, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(GuardarOut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(BtnCancelarOut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(NuevoOut, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(BtnSalirOut, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel3.getAccessibleContext().setAccessibleName("Productos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(476, 477));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

//Evento de Busqueda del primer 
    private void BtnPrimerOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnPrimerOutActionPerformed
        // TODO add your handling code here:
        try{
		resultado.first();
		actualizar();
		}
		catch(Exception f){}
    }//GEN-LAST:event_BtnPrimerOutActionPerformed
//Evento de Busqueda del anterior 
    private void BtnAnteriorOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAnteriorOutActionPerformed
        // TODO add your handling code here:
        try{
            if (resultado.isBeforeFirst()==false){
		resultado.previous();
		if (resultado.isBeforeFirst()==true)
                   {resultado.first();}
                   actualizar();
                    }
		}
	catch(Exception p){}
    }//GEN-LAST:event_BtnAnteriorOutActionPerformed
   
    private void BtnBuscarOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBuscarOutActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_BtnBuscarOutActionPerformed
   //Evento de Busqueda del siguiente
    private void BtnSiguienteOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSiguienteOutActionPerformed
        // TODO add your handling code here:
        try{
            if (resultado.isAfterLast()==false){
                resultado.next();
		if (resultado.isAfterLast()==true)
		   {resultado.last();}
                       actualizar();
			}
			}
		catch(Exception p){}
    }//GEN-LAST:event_BtnSiguienteOutActionPerformed
     //Evento de Busqueda del ultimo 
    private void BtnUltimoOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnUltimoOutActionPerformed
        // TODO add your handling code here:
        try{
            resultado.last();
            actualizar();
            }
            catch(Exception a){}
    }//GEN-LAST:event_BtnUltimoOutActionPerformed

    private void TxtPVPKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TxtPVPKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_TxtPVPKeyTyped

    private void TxtPVPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TxtPVPActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_TxtPVPActionPerformed

    private void TxtMontoOutFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TxtMontoOutFocusLost
        // TODO add your handling code here:
         if (TxtMontoOut.getText().length()==0)
	  {TxtMontoOut.setText("0.00");}
            double precio;
		precio = Double.parseDouble(TxtMontoOut.getText());
		NumberFormat redondeo = NumberFormat.getInstance();
		redondeo.setMaximumFractionDigits(2);
		redondeo.setMinimumFractionDigits(2);
                String sueldoletra=(redondeo.format(precio));
		String letra=("");
		String preciocambiado=("");
		for (int x=1;x<=sueldoletra.length();x++){
		letra=sueldoletra.substring(x-1,x);
                if (letra.equals(",")==true)
                         {letra=".";}
                else if(letra.equals(".")==true)
                         {letra="";}
                preciocambiado=preciocambiado+letra;
                    }
                TxtMontoOut.setText(preciocambiado);
    }//GEN-LAST:event_TxtMontoOutFocusLost

    private void TxtMontoOutKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TxtMontoOutKeyTyped
        // TODO add your handling code here:
         boolean punto;
                                    char caracter;
				    caracter=(evt.getKeyChar()+"").charAt(0);
				    if (TxtMontoOut.getText().length()<10)
				       {if ((caracter+"").matches("[0-9.]"))
				            {if (caracter=='.')
				               {punto=false;
				            	for (int x=0;x<TxtMontoOut.getText().length();x++){
				            		if (TxtMontoOut.getText().substring(x,x+1).equals("."))
				            		{punto=true;}
				            	}
				                if (punto==false)
				                    {evt.setKeyChar(caracter);}
				                 else
				                    {evt.consume();}
				                }
				             else
				    	        {evt.setKeyChar(caracter);}
				            }
				        else
				           {evt.consume();}
				    	}
				    else
				        {evt.consume();}       
              
    }//GEN-LAST:event_TxtMontoOutKeyTyped

    private void BtnSalirOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSalirOutActionPerformed
        // TODO add your handling code here:
        int resp=JOptionPane.showConfirmDialog(null,"Desea salir del formulario?","Salir del formulario",0);
        if(resp==0)
        {dispose();}
    }//GEN-LAST:event_BtnSalirOutActionPerformed

    private void BtnCancelarOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelarOutActionPerformed
        // TODO add your handling code here:
        try{
            int respuesta=JOptionPane.showConfirmDialog(null, "Desea descartar los datos ingresados?", "Cancelar ingresos",0, 3);
            if (respuesta==0){
                sentencia.executeQuery("select * from SALIDAS order by id_out");
                resultado=sentencia.getResultSet();

                habilitaguacan();

                if (resultado.next()==false)
                {if (nuevoreg==false)
                    {JOptionPane.showMessageDialog(null,"Los datos de esta entrada acaban de ser eliminados por otro usuario del sistema!","Vendedor inexistente",0);
                    }
                    limpiar();
                    vacio();
                }
                else
                {if(nuevoreg==true)
                    {resultado.last();
                        actualizar();
                    }
                    else
                    {elcodigo=TxtIdOut.getText();
                        //encuentra();
                    }
                }
            }
        }
        catch(Exception s){}

    }//GEN-LAST:event_BtnCancelarOutActionPerformed

    private void GuardarOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarOutActionPerformed

         // TODO add your handling code here:
        double Monto=Double.parseDouble(TxtMontoOut.getText());
        if
        
       (TxtObservacionOut.getText().trim().length()==0){
            JOptionPane.showMessageDialog(null,"Escriba una Observacion!", "Error de almacenamiento", 2);
            TxtObservacionOut.requestFocus();
        }
        

        else if(Monto==0){

            JOptionPane.showMessageDialog(null,"Ingrese el Valor de Ingreso!", "Error de almacenamiento", 2);
            TxtMontoOut.requestFocus();
        }
       
        else{
            guardar();
        }

    }//GEN-LAST:event_GuardarOutActionPerformed

    private void NuevoOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NuevoOutActionPerformed
        // TODO add your handling code here:
        cargarfecha();
        nuevoreg=true;
        limpiar();
        generacodigo();
        habilitanuemod();
        TxtObservacionOut.requestFocus();

    }//GEN-LAST:event_NuevoOutActionPerformed

    private void TxtFechaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TxtFechaFocusGained
        // TODO add your handling code here:
        //limpiar();
        cargarfecha();
        // CargarTabla();
    }//GEN-LAST:event_TxtFechaFocusGained
   
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(f_salidas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new f_salidas().setVisible(true);
            }
        });
    }
    
    
    //Metodo que genera automaticamente el codigo de  de manera incremental
    public void generacodigo(){
		try{
			if (xregistros==0)
			   {TxtIdOut.setText("OU0001"); }
			else{
			   resultado.last();
			   String numerocad=(resultado.getString("id_out").substring(2));
			   String cadnuevo=String.valueOf(Integer.valueOf(numerocad)+1);
			   int x;
			   String ceros=("");
			   for (x=1;x<=4-cadnuevo.length();x++)
			       {ceros=ceros+"0";}
			   TxtIdOut.setText("OU"+ceros+cadnuevo);
			   if (cadnuevo.length()==5)
			      {TxtIdOut.setText("");
			      JOptionPane.showMessageDialog(null, "No se puede generar el codigo. Se ha superado la capacidad del sistema!","Desbordamiento de valores",0);
                              dispose();
                              }
			}
		}
		catch(SQLException | NumberFormatException | HeadlessException g){
		}
	}
    
    
    
    
    public void conectar(){
		try
	    {Class.forName("com.mysql.jdbc.Driver").newInstance();
	     conexion=DriverManager.getConnection("jdbc:mysql://localhost/facturacion","root","city123");
		 sentencia=conexion.createStatement();
		 sentencia.executeQuery("SELECT * FROM SALIDAS ORDER BY ID_OUT");
		 resultado=sentencia.getResultSet();
		 if (resultado.next()==false)
		    {vacio();
		     xregistros=0;
                    }
		 else
		    {xregistros=1;
                     resultado.last();
		     actualizar();
			 }
	    }
	    catch( ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e )
	    {JOptionPane.showMessageDialog(null,"Ha ocurrido un error al intentar acceder los datos de las salidas!", "Error de acceso", 2);
        }
	}
    
        public void eliminar(){
        
            try{
               {sentencia=conexion.createStatement();
                sentencia.executeUpdate("DELETE FROM SALIDAS WHERE ID_OUT='"+TxtIdOut.getText()+"'");
		JOptionPane.showMessageDialog(null,"Los datos de la Salida han sido eliminados!", "Eliminacion de datos", 1);
		sentencia.executeQuery("SELECT * FROM SALIDAS ORDER BY ID_OUT");
		resultado=sentencia.getResultSet();
                        if (resultado.next()==false)
			    {xregistros=0;
				limpiar();
				vacio();}
			else
			    {xregistros=1;
			     resultado.last();
			     actualizar();
				 }
			  }
			}
		  catch( Exception e ){
			JOptionPane.showMessageDialog(null,"Ha ocurrido un error al intentar eliminar los datos de la entrada!", "Error de eliminaciòn", 2);
		}     
        
        }
        
        
        
        
    
        private void guardar(){
        
         try {
            // TODO add your handling code here:
             String fechasql=(TxtFecha.getText().substring(6)+"-"+TxtFecha.getText().substring(3,5)+"-"+TxtFecha.getText().substring(0,2));
              if (nuevoreg==true){ //autoriza la peticcion de nuevo sino permite el update
               
                  sentencia=conexion.createStatement();
                
                sentencia.executeUpdate("INSERT INTO SALIDAS (ID_OUT,MONTO_OUT,OBSERVACION,FECHA) VALUES('"+TxtIdOut.getText()+
					                 "','"+TxtMontoOut.getText()+"','"+TxtObservacionOut.getText()+"','"+fechasql+"')");
                
                
                xregistros=1;
              }
              else
              {
              sentencia.executeUpdate("UPDATE SALIDAS SET OBSERVACION='"+TxtObservacionOut.getText()+"',MONTO_OUT='"+TxtMontoOut.getText()+ "'WHERE ID_OUT='"+TxtIdOut.getText()+"'");
                            
              }
              
              sentencia.executeQuery("SELECT * FROM SALIDAS ORDER BY ID_OUT");
		 resultado=sentencia.getResultSet();
		
                 if (nuevoreg==true)
			{resultado.last();
			 actualizar();}
		 else
		    {elcodigo=TxtIdOut.getText();
		 encuentra();}
		 JOptionPane.showMessageDialog(null,"Los datos de la salida han sido guardados!", "Almacenamiento de datos", 1);
		 habilitaguacan();
              
           
                                
              
        } 
         
         
         catch (SQLException ex) {
            Logger.getLogger(f_salidas.class.getName()).log(Level.SEVERE, null, ex);
        }
         
	}
        
        private void encuentra(){
		try{
			sentenciaxreg=conexion.createStatement();
			sentenciaxreg.executeQuery("SELECT COUNT(ID_OUT)AS CUANTOSOUT FROM SALIDAS");
			resultadoxreg=sentenciaxreg.getResultSet();
			resultadoxreg.last();
			resultado.first();
			for (int x=1;x<=resultadoxreg.getInt("CUANTOSOUT");x++)
			{   if (resultado.getString("id_out").equals(elcodigo)==true)
			 	{break;
				}
				resultado.next();
			}
			if (resultado.isAfterLast()==true)
			{  JOptionPane.showMessageDialog(null,"La salida no pudo ser localizada!", "Error de busqueda", 2);
			   resultado.last();
			}
			actualizar();
			}
		catch(Exception m)
			{JOptionPane.showMessageDialog(null,"La salida no pudo ser localizada!", "Error de busqueda", 2);
			}
	}
        
        
    
         private void actualizar(){
		try{
	 	 
                 TxtIdOut.setText(resultado.getString("id_out"));
		 TxtObservacionOut.setText(resultado.getString("observacion"));
                 TxtMontoOut.setText(resultado.getString("monto_out"));
		
		 
		}
		catch (Exception m){
		}
	}
       
        
    
        private void limpiar(){
		   
        TxtIdOut.setText("");
	TxtObservacionOut.setText("");
        TxtMontoOut.setText("0.00");
        }
        
    
    
        public void habilitanuemod(){
		NuevoOut.setEnabled(false);
		//BtnModificar.setEnabled(false);
		GuardarOut.setEnabled(true);
		BtnCancelarOut.setEnabled(true);
		//BtnEliminar.setEnabled(false);
		BtnPrimerOut.setEnabled(false);
		BtnAnteriorOut.setEnabled(false);
		BtnBuscarOut.setEnabled(false);
		BtnSiguienteOut.setEnabled(false);
		BtnUltimoOut.setEnabled(false);
	}
        public void habilitaguacan(){
		NuevoOut.setEnabled(true);
		//BtnModificar.setEnabled(true);
		GuardarOut.setEnabled(false);
		BtnCancelarOut.setEnabled(false);
		//BtnEliminar.setEnabled(true);
		
                BtnPrimerOut.setEnabled(true);
		BtnAnteriorOut.setEnabled(true);
		BtnBuscarOut.setEnabled(true);
		BtnSiguienteOut.setEnabled(true);
		BtnUltimoOut.setEnabled(true);
		
               // TxtNombre.setEnabled(false);
		//TxtPrecio.setEnabled(false);
		//TxtCantidad.setEnabled(false);
	}
    
    
    
    
    
        
        private void vacio(){
            
               
        }
         private void vacioout(){
            
               
        }
        
        public void cargarfecha(){
		String fechactual=new String("");
		String dia=new String(String.valueOf(lafecha.get(lafecha.DAY_OF_MONTH)));
		if (dia.length()==1)
		   {dia="0"+dia;}
		String mes=new String(String.valueOf(lafecha.get(lafecha.MONTH)+1));
		if (mes.length()==1)
		   {mes="0"+mes;}
		String año=new String(String.valueOf(lafecha.get(lafecha.YEAR)));
		fechactual=dia+"/"+mes+"/"+año;
	  TxtFecha.setText(fechactual);
          
          
	}
    
       
        
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnAnteriorOut;
    private javax.swing.JButton BtnBuscarOut;
    private javax.swing.JButton BtnCancelarOut;
    private javax.swing.JButton BtnPrimerOut;
    private javax.swing.JButton BtnSalirOut;
    private javax.swing.JButton BtnSiguienteOut;
    private javax.swing.JButton BtnUltimoOut;
    private javax.swing.JButton GuardarOut;
    private javax.swing.JButton NuevoOut;
    private javax.swing.JTextField TxtFecha;
    private javax.swing.JTextField TxtIdOut;
    private javax.swing.JTextField TxtMontoOut;
    private javax.swing.JTextField TxtObservacionOut;
    private javax.swing.JTextField TxtPVP;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelIdOut;
    private javax.swing.JLabel jLabelMontoOut;
    private javax.swing.JLabel jLabelObservaciones;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    // End of variables declaration//GEN-END:variables
}
